package firstappdemo.controller;

import firstappdemo.domain.Person;
import firstappdemo.domain.User;
import firstappdemo.repository.JxlsUtils;
import firstappdemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liujs@centaline.com.cn
 * @date 2020/2/12 14:02
 */
@RestController
public class UserController {
    private final UserRepository userRepository;

    @Autowired
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostMapping("/person/save")
    public User Save(@RequestParam String name) {
        User user = new User();
        user.setName(name);
        if (userRepository.save(user)) {
            System.out.printf("用户对象: %s 保存成功！ \n", user);
        }
        return user;
    }

    @GetMapping("/downExcel")
    public void down() throws Exception {
        // 模板位置，输出流
        String templatePath = "/xlstemplate/template_2.xls";// /xlstemplate/template2.xls
        // templatePath = TestMain.class.getResource(templatePath).getPath();
        OutputStream os = new FileOutputStream("E:/out.xls");

// 一个装有对象数据的链表
        List<Person> persons = new ArrayList<Person>();
        Person p1 = new Person("001", "张三", 18);
        Person p2 = new Person("002", "李四", 19);
        Person p3 = new Person("003", "王五", 20);
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("person", persons);    // 把链表放进model中

        JxlsUtils.exportExcel(templatePath, os, model);
        os.close();
        System.out.println("完成");
    }
}
